import logging

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from haystack.views import SearchView

from .models import GoodsCategory, SKU, GoodsVisitCount
from .utils import get_breadcrumb,get_goods_and_spec
from django.utils import timezone
import datetime
from django.core.paginator import Paginator, EmptyPage
logger = logging.getLogger('django')


class ListView(View):
    """商品列表页"""

    def get(self, request, category_id):
        '''列表页展示的数据'''
        # 1. 接收参数:
        # 当前页码:
        page_num = request.GET.get('page')
        # 每页数量:
        page_size = request.GET.get('page_size')

        # 2.判断category_id是否正确
        try:
            # 获取三级菜单分类信息:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseNotFound('GoodsCategory 不存在')
        # 调用函数, 获取面包屑:
        breadcrumb = get_breadcrumb(category)

        # 排序方式:
        sort = request.GET.get('ordering')
        try:
            skus = SKU.objects.filter(category=category,
                                      is_launched=True).order_by(sort)
        except SKU.DoesNotExist:
            return http.HttpResponseNotFound('GoodsCategory 不存在')

        paginator = Paginator(skus, 5)
        # 获取每页商品数据
        try:
            page_skus = paginator.page(page_num)
        except EmptyPage:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound('empty page')
        # 获取列表页总页数
        total_page = paginator.num_pages

        # 定义列表:
        list = []
        # 整理格式:
        for sku in page_skus:
            list.append({
                'id': sku.id,
                'default_image_url': sku.default_image_url,
                'name': sku.name,
                'price': sku.price
            })
        # 拼接传给前端的数据:
        dict = {
            # 面包屑导航
            'breadcrumb': breadcrumb,
            'list': list,
            'count': total_page
        }
        # 把数据变为 json 发送给前端
        return http.JsonResponse(dict)


class HotGoodsView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        """提供商品热销排行 JSON 数据"""
        # 根据销量倒序
        skus = SKU.objects.filter(category_id=category_id,
                                  is_launched=True).order_by('-sales')[:5]

        # 转换格式:
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'default_image_url':sku.default_image_url,
                'name':sku.name,
                'price':sku.price
            })
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'OK',
                                  'hot_skus': hot_skus})

class MySearchView(SearchView):
    '''重写SearchView类'''
    def create_response(self):
        page = self.request.GET.get('page')
        # 获取搜索结果
        context = self.get_context()
        data_list = []
        for sku in context['page'].object_list:
            data_list.append({
                'id':sku.object.id,
                'name':sku.object.name,
                'price':sku.object.price,
                'default_image_url':sku.object.default_image_url,
                'searchkey':context.get('query'),
                'page_size':context['page'].paginator.num_pages,
                'count':context['page'].paginator.count
            })
        # 拼接参数, 返回
        return http.JsonResponse(data_list, safe=False)

class DetailView(View):

    def get(self, request, sku_id):
        """提供商品详情页"""

        # 商品分类菜单
        categories = get_breadcrumb()

        # 调用封装的函数, 根据 sku_id 获取对应的
        # 1. 类别( sku )
        # 2. 商品( goods )
        # 3. 商品规格( spec )
        data = get_goods_and_spec(sku_id, request)

        # 获取面包屑导航:
        breadcrumb = get_breadcrumb(data['goods'].category3)

        # 拼接参数，生成静态 html 文件
        context = {
            'categories': categories,
            'goods': data.get('goods'),
            'specs': data.get('goods_specs'),
            'sku': data.get('sku'),
            'breadcrumb':breadcrumb
        }

        return render(request, 'detail.html', context)

class DetailVisitView(View):
    """详情页分类商品访问量"""

    def post(self, request, category_id):
        """记录分类商品访问量"""

        # 根据传入的 category_id 值, 获取对应类别的商品:
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('缺少必传参数')

        # 获取今天的日期:
        # 先获取时间对象
        t = timezone.localtime()
        # 根据时间对象拼接日期的字符串形式:
        today_str = '%d-%02d-%02d' % (t.year, t.month, t.day)
        # 将字符串转为日期格式:
        today_date = datetime.datetime.strptime(today_str, '%Y-%m-%d')
        try:
            # 将今天的日期传入进去, 获取该商品今天的访问量:
            # 查询今天该类别的商品的访问量
            counts_data = category.goodsvisitcount_set.get(date=today_date)
        except GoodsVisitCount.DoesNotExist:
            # 如果该类别的商品在今天没有过访问记录，就新建一个访问记录
            counts_data = GoodsVisitCount()

        try:
            # 更新模型类对象里面的属性: category 和 count
            counts_data.category = category
            counts_data.count += 1
            counts_data.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('服务器异常')

        # 返回:
        return http.JsonResponse({'code': 200, 'errmsg': 'OK'})